package panels;

import interfaces.ConnectNo;
import interfaces.Shoot;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.rmi.NotBoundException;
import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.ArrayList;



/**
 *
 * @author ubu
 */
public class ConnectionPanel extends javax.swing.JPanel implements MouseListener{

    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private boolean started = false;
    private static int ID;
    private boolean serverRunning;
    public boolean connected= true;
    private String host;
    
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration 
    /**
     * Creates new form ConnectionPanel
     */
    public ConnectionPanel() {
        try {
			initComponents();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        jLabel1.setVisible(connected);
        jTextField1.setVisible(connected);
        jLabel2.setVisible(connected);
        jComboBox1.setVisible(connected);
        jButton1.setVisible(connected);
        jLabel3.setVisible(!connected);
        
        ActionListener connectListener = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                connect();
                            
            }
        };
        jButton1.addActionListener(connectListener);
    }
    private String[] getHosts() throws Exception
    {
    	 ArrayList<String> list = new ArrayList<String>();
    		  // Open the file that is the first 
    		  // command line parameter
    		  FileInputStream fstream = new FileInputStream("Servers.txt");
    		  // Get the object of DataInputStream
    		  DataInputStream in = new DataInputStream(fstream);
    		  BufferedReader br = new BufferedReader(new InputStreamReader(in));
    		  String strLine;
    		  //Read File Line By Line
    		  while ((strLine = br.readLine()) != null)   {
    		  // Print the content on the console
    		  list.add(strLine);
    		  }
    		  //Close the input stream
    		  in.close();
    		String[] returned =  new String[list.size()];
    		for(int i=0;i<returned.length ;i++)
    		{
    			returned[i] = list.get(i);
    		}
    		return returned;
    }
    private void initComponents() throws Exception {

        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        jButton1 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        

        setPreferredSize(new java.awt.Dimension(200, 200));

        jLabel1.setText("Login");

        jTextField1.setText("jTextField1");

        jLabel2.setText("Server");

        //jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "localhost" }));
        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(getHosts()));

        jButton1.setText("Connect");

        jLabel3.setText("Connectng...");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 36, Short.MAX_VALUE)
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(38, 38, 38))
            .addGroup(layout.createSequentialGroup()
                .addGap(49, 49, 49)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addComponent(jLabel3)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel3)
                .addContainerGap(38, Short.MAX_VALUE))
        );
    }// </editor-fold>         
    
    private void connect()
    {
        /*
         * AddPlayer toServer
         */
    	ConnectNo service;
    	try {
            if (System.getSecurityManager() == null)
                    {
                            System.setSecurityManager
                            (new RMISecurityManager());
                    }

                    // Call registry for PowerService
            		Registry registry = LocateRegistry.getRegistry();
                    service = (ConnectNo)registry.lookup(interfaces.ConnectNo.SERVICE_NAME);
                    service.setCon(service.getCon()+1);
                    setID(service.getCon());
                    System.out.println("I am no:" + getID());
        } //main end
        catch (NotBoundException ex) {
        	System.out.println("No such service avaliable");
            //Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex);
        } catch (RemoteException ex) {
        	System.out.println("Server not started yet");
           // Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex);
        }
    	
    	
        Component[] Comp = this.getComponents();
        for(int i=0;i<Comp.length;i++)
        {
            if(Comp[i].equals(jLabel3))
            Comp[i].setVisible(connected);
            else
                
                Comp[i].setVisible(!connected);
            
        }
        
        this.setStarted(true);
        this.setServerRunning(true);
        setHost(jComboBox1.getSelectedItem().toString());
        //System.out.println("connect!");
    }
    
                  

    @Override
    public void mouseClicked(MouseEvent me) {
       
    }

    @Override
    public void mousePressed(MouseEvent me) {
        
        
    }

    @Override
    public void mouseReleased(MouseEvent me) {
        
    }

    @Override
    public void mouseEntered(MouseEvent me) {
        
    }

    @Override
    public void mouseExited(MouseEvent me) {
       
    }
    
        public boolean isStarted() {
        return started;
    }

    public void setStarted(boolean started) {
        this.started = started;
    }

	public static int getID() {
		return ID;
	}

	public static void setID(int iD) {
		ID = iD;
	}

	public synchronized void setServerRunning(boolean serverRunning) {
		this.serverRunning = serverRunning;
	}

	public synchronized boolean isServerRunning() {
		return serverRunning;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public String getHost() {
		return host;
	}
}